package core;

import java.io.BufferedReader;
import java.io.FileReader;

import spatialindex.rtree.RTree;
import spatialindex.spatialindex.ISpatialIndex;
import spatialindex.spatialindex.Point;
import spatialindex.storagemanager.DiskStorageManager;
import spatialindex.storagemanager.IBuffer;
import spatialindex.storagemanager.IStorageManager;
import spatialindex.storagemanager.PropertySet;
import spatialindex.storagemanager.RandomEvictionsBuffer;
import util.Constants;
import util.NBGStrParser;

public class TimePartition {

	int startTime, endTime;
	String RTreeFile;
	ISpatialIndex tree;

	public TimePartition(int startTime, int endTime, String rTreeFile)
			throws Exception {
		this.startTime = startTime;
		this.endTime = endTime;
		this.RTreeFile = rTreeFile;
		PropertySet ps = new PropertySet();
		// overwrite the file if it exists.
		ps.setProperty("Overwrite", true);
		// fileName, .idx and .dat extensions will be added.
		ps.setProperty("FileName", RTreeFile);
		Integer i = new Integer(4096);
		ps.setProperty("PageSize", i);
		IStorageManager diskfile = new DiskStorageManager(ps);

		IBuffer file = new RandomEvictionsBuffer(diskfile, 10, false);
		PropertySet ps2 = new PropertySet();

		Double f = new Double(0.7);
		ps2.setProperty("FillFactor", f);

		i = new Integer(Constants.rTreeCapacity);
		ps2.setProperty("IndexCapacity", i);
		ps2.setProperty("LeafCapacity", i);
		// Index capacity and leaf capacity may be different.

		i = new Integer(2);
		ps2.setProperty("Dimension", i);

		tree = new RTree(ps2, file);

	}

	/**
	 * Load RTree with NBGData file Assume the NBG data file has all data
	 * between start_time and end_time
	 * 
	 * @param NBGDataFile
	 */
//	public void LoadRTree(String NBGDataFile) {
//		BufferedReader in;
//		try {
//			in = new BufferedReader(new FileReader(NBGDataFile));
//			String str;
//			NBGStrParser dataParser = new NBGStrParser();
//			int count = 0;
//			while ((str = in.readLine()) != null) {
//				// Create a disk based storage manager.
//				dataParser.setNBGStr(str);
//
//				count++;
//			}
//			in.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//
//	}

	public void insertData(String nbgStr, NBGStrParser dataParser, int pointId) {
		double[] coords = { dataParser.getCurrPosx(), dataParser.getCurrPosy() };
		tree.insertData(nbgStr.getBytes(), new Point(coords), pointId);
	}
}
